package com.kellyfeng.spittr;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.kellyfeng.spittr.repository.SpitterRepository;

@Configuration
@EnableGlobalMethodSecurity(securedEnabled=true, prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	@Autowired
	private SpitterRepository spitterRepository;

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.csrf().disable();
	//	.antMatchers(HttpMethod.POST, "/spittles").access("hasRole('USER')")
	//	.antMatchers("/**").permitAll()
		http
		.authorizeRequests()
		.antMatchers("/static/**").permitAll()
		.antMatchers("/style.css").permitAll()
		.antMatchers("/login").permitAll()
		.antMatchers("/spitter/register").permitAll()
		.antMatchers("/**").access("hasRole('USER')")
		.and()
		.formLogin()
		.loginPage("/login")
		.and()
		.logout()
		.logoutSuccessUrl("/")
		.and()
		.rememberMe()
		.tokenValiditySeconds(24199200)
		.key("spittrKey");
	    
	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth
		.userDetailsService(new UserDetailsService() {
			@Override
			public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
				UserDetails userDetails = spitterRepository.findByUsername(username);
				if (userDetails != null) {
					return userDetails;
				}
				throw new UsernameNotFoundException("User '" + username + "' not found.");
			}
		});
	}
}
